package lion.dev.lang;

import java.io.File;
import java.io.InputStream;

import org.apache.commons.io.IOUtils;

/**
 * 对Runtime.getRuntime().exec()方法的封装，更方便的调用如<br/>
 *
 * <pre>
 * 	Shell shell = Shell.getShell();
 * 	shell.execString("cmd /C dir");
 *  等同于
 *  shell.execString("cmd","/c","dir");
 * </pre>
 *
 * <pre>
 * time   2013 2013年12月13日 上午10:56:15
 * mail   hl_0074@sina.com
 * </pre>
 *
 * @author lion
 */
public class Shell {

	private Process process;
	private File dir = null;

	private Shell() {

	}

	private Shell(File dir) {

		this.dir = dir;
	}

	public static Shell getShell() {

		return new Shell();
	}

	public static Shell getShell(String dir) {

		return getShell(new File(dir));
	}

	public static Shell getShell(File dir) {

		return new Shell(dir);
	}

	public void exec(String command) throws Exception {

		exec(command.split(" "));
	}

	public void exec(String... commands) throws Exception {

		ProcessBuilder pb = new ProcessBuilder(commands);
		pb.directory(dir);
		process = pb.start();
	}

	public InputStream execStream(String command) throws Exception {

		return execStream(command.split(" "));
	}

	public InputStream execStream(String... commands) throws Exception {

		ProcessBuilder pb = new ProcessBuilder(commands);
		pb.redirectErrorStream(true);
		pb.directory(dir);
		process = pb.start();
		InputStream ins = process.getInputStream();

		return ins;
	}

	public String execString(String command) throws Exception {

		return execString(command.split(" "));
	}

	public String execString(String... command) throws Exception {

		InputStream is = execStream(command);
		return IOUtils.toString(is, "UTF-8");
	}

	public int getStatus() {

		if (process != null) {
			int exit = 0;
			try {
				exit = process.waitFor();
			} catch (InterruptedException e) {
			}
			return exit;
		}
		return 0;
	}

	public void close() {

		if (process != null) {
			process.destroy();
		}
	}

	public static boolean isWindowsMode() {

		return System.getProperty("os.name").toLowerCase().indexOf("windows") >= 0;
	}

	public static boolean isLinuxMode() {

		return !isWindowsMode();
	}
}
